package org.tinygame.herostory;

import com.google.protobuf.GeneratedMessageV3;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinygame.herostory.model.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

/**
 * @author shkstart
 * @create 2022-05-04 17:03
 */
public class GameMsgHandler extends SimpleChannelInboundHandler<Object> {
    private static final Logger LOGGER= LoggerFactory.getLogger(GameMsgHandler.class);
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Broadcaster.addChannel(ctx.channel());
    }

    /**
     * 处理用户退出操作
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);

        //关闭该用户的群发通道
        Broadcaster.removeChannel(ctx.channel());
        //拿到用户id
        Integer userId=(Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if(null==userId){
            return;
        }
        //从字典中删除该用户
        UserManager.removeUserById(userId);
        GameMsgProtocol.UserQuitResult.Builder resultBuilder=GameMsgProtocol.UserQuitResult.newBuilder();
        resultBuilder.setQuitUserId(userId);

        //构建结果并发送
        GameMsgProtocol.UserQuitResult newResult =resultBuilder.build();
        Broadcaster.broadcast(newResult);

    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof GeneratedMessageV3){
            MainThreadProcessor.GetInstance().process(ctx,(GeneratedMessageV3)msg);
        }
    }


}
